import React, { useState, useRef } from 'react';
import { Button, Form, Space, Alert, message } from 'antd';
import { ModalForm, ProFormUploadDragger } from '@ant-design/pro-form';
import { ImportOutlined, DownloadOutlined } from '@ant-design/icons';
import request from '@/utils/request';
import { downloadFile } from '@/utils/utils';

const ImportForm = (props) => {
  const { onSuccess, action, templateUrl, title } = props;
  const [fileList, setFileList] = useState([]);
  const [uploading, setUploading] = useState(false);
  const formRef = useRef();

  return (
    <ModalForm
      title={title || '导入Excel文件'}
      trigger={
        <Button key="import" type="default" loading={uploading}>
          <ImportOutlined /> 导入
        </Button>
      }
      onVisibleChange={(visible) => {
        if (!visible) {
          setFileList([]);
          formRef.current.resetFields();
        }
      }}
      formRef={formRef}
      onFinish={async () => {
        const formData = new FormData();
        formData.append('file', fileList[0]);
        setUploading(true);
        const result = await request(action, {
          method: 'post',
          data: formData,
        });
        setUploading(false);
        if (result.success && result.data === null) {
          message.success('导入成功');
          setFileList([]);
          formRef.current.resetFields();
          await onSuccess();
          return true;
        }
        if (result.success) {
          message.warning('处理完成，但有错误，请检查！');
          downloadFile(result.data);
        } else {
          message.error(result.message);
        }
        return false;
      }}
      submitter={{
        searchConfig: {
          submitText: (
            <>
              <ImportOutlined /> 立即导入
            </>
          ),
        },
      }}
      modalProps={{
        maskClosable: false,
      }}
    >
      <Form.Item>
        <Alert
          message="请点击[下载模板]填充完成后再上传进行导入"
          type="info"
          showIcon
          action={
            <Space direction="vertical">
              <Button
                type="dashed"
                onClick={() => {
                  window.location.href = templateUrl;
                }}
              >
                <DownloadOutlined /> 下载模板
              </Button>
            </Space>
          }
        />
      </Form.Item>
      <ProFormUploadDragger
        name="file"
        accept={'.xls,.xlsx'}
        fieldProps={{
          fileList,
          beforeUpload: (file) => {
            setFileList([file]);
            return false;
          },
        }}
        description={'只支持.xls,.xlsx 文件格式上传。'}
        rules={[{ required: true, message: '请选择上传要导入的Excel文件' }]}
      />
    </ModalForm>
  );
};
export default ImportForm;
